import React, { useState } from 'react'
import classnames from 'classnames'
import PropTypes from 'prop-types'
import _ from 'lodash'
import PartyShower from './PartyShower'
import AgentShower from './AgentShower'
import style from './PartyBlock.module.less'

// 格式化当事人和代理人数据
function formatList (partys, agents) {
  const partyIdMap = {}
  partys.forEach(li => {
    partyIdMap[li.id] = li
  })
  agents.forEach(li => {
    li.partyids = li.party.map(o => o.partyid)
    li.party = li.party.map(o => {
      const p = partyIdMap[o.partyid]
      if (!p) {
        return null
      }
      if (p.agents instanceof Array) {
        p.agents.push(li)
      } else {
        p.agents = [li]
      }
      return p
    }).filter(o => o)
  })
  const noAgentPartys = []
  const agentPartyMap = {}
  partys.forEach(li => {
    if (li.agents instanceof Array) {
      const ids = li.agents.map(li => li.id)
      ids.sort()
      const key = ids.join()
      if (agentPartyMap[key] instanceof Array) {
        agentPartyMap[key].push(li)
      } else {
        agentPartyMap[key] = [li]
      }
    } else {
      noAgentPartys.push(li)
    }
  })
  const values = Object.values(agentPartyMap)
  return [...values, ...noAgentPartys]
}

function splitArray (list) {
  const r = []
  const len = list.length
  list.forEach((li, i) => {
    r.push(li)
    if (i !== len - 1) {
      r.push(<span key={`dom-${i}`}>、</span>)
    }
  })
  return r
}

// 行
function Line ({ isApply = false, partyList = [], agentList = [], showParty = () => {}, showAgent = () => {} }) {
  const names = classnames(style.line, { [style.respondent]: !isApply })
  const label = isApply ? '申' : '被'
  const partys = formatList(_.cloneDeep(partyList), _.cloneDeep(agentList))
  const doms = partys.map((li, i) => {
    if (li instanceof Array) {
      return <PartyAgent data={li} key={i} showParty={showParty} showAgent={showAgent} />
    }
    return <Party data={li} key={i} showParty={showParty} />
  })
  return (
    <div className={names}>
      <div className={style.label}>{label}</div>
      <div className={style.list}>
        {
          splitArray(doms)
        }
      </div>
    </div>
  )
}

function PartyAgent ({ data, showParty = () => {}, showAgent = () => {} }) {
  const result = []
  const agents = data[0].agents
  if (data.length === 1) {
    result.push(<Party key='1' data={data[0]} showParty={showParty} />)
  } else {
    const r = []
    data.forEach((li, i) => {
      r.push(<Party key={i} data={data[i]} showParty={showParty} />)
      if (i !== data.length - 1) {
        r.push(<span key={`d-${i}`}>、</span>)
      }
    })
    result.push((
      <span key='party'>
        {r}
      </span>
    ))
  }
  result.push(<Agent key='agent' data={agents} showAgent={showAgent} />)
  return (
    <span>
      {result}
    </span>
  )
}

function Party ({ data, showParty = () => {} }) {
  const className = classnames(style.person, { [style.disabled]: data.status === 0 })
  return (
    <span className={className}>
      <span className={style['person-name']} onClick={() => showParty(data)}>{data.name}</span>
      {data.status === 0 && <span>（终结）</span>}
    </span>
  )
}

function Agent ({ data, showAgent = () => {} }) {
  const r = []
  data.forEach((d, i) => {
    const className = classnames(style.person, { [style.disabled]: d.status === 0 })
    r.push((
      <span key={i} className={className}>
        <span className={style['person-name']} onClick={() => showAgent(d)}>{d.name}{d.status === 0 && <span>（终结）</span>}</span>
        {d.structure && <span> - {d.structure}</span>}
      </span>
    ))
    if (i !== data.length - 1) {
      r.push(<span key={`d-${i}`}>、</span>)
    }
  })
  return (
    <span>
      <span>（代理人：</span>
      {r}
      <span>）</span>
    </span>
  )
}

function Main ({ caseDetail: d }) {
  const [party, setParty] = useState(null)
  const [agent, setAgent] = useState(null)
  if (!d) {
    return (<span />)
  }
  return (
    <div className={style.container}>
      <PartyShower data={party} hide={() => setParty(null)} />
      <AgentShower data={agent} hide={() => { setAgent(null) }} />
      <Line isApply partyList={d.applicants} agentList={d.applicant_agents} showParty={d => setParty(d)} showAgent={(d, l) => { setAgent(d) }} />
      <Line partyList={d.respondents} agentList={d.respondents_agents} showParty={d => setParty(d)} showAgent={(d, l) => { setAgent(d) }} />
    </div>
  )
}

Main.propTypes = {
  caseDetail: PropTypes.object
}

Main.defaultProps = {
  caseDetail: {}
}

export default Main
